package com.mp.config;

import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 *  扩展springMvc功能，实现WebMvcConfigurer
 * @author:
 * @date:
 */
@Configuration
public class MvcConfig{
    //文件真实路径
    @Value("${file.really-path}")
    public  String reallyPath;
    //文件虚拟路径
    @Value("${file.virtual-path}")
    public  String virtualPath;


    //所有的WebMvcConfigurer组件都会一起起作用
    @Bean//将adapter添加到容器中
    public WebMvcConfigurer getWebMvcConfigurer(){
        return  new  WebMvcConfigurer(){
            //配置上传图片的虚拟路径
            @Override
            public void addResourceHandlers(ResourceHandlerRegistry registry) {
                registry.addResourceHandler(virtualPath+"/**").
                        addResourceLocations("file:/"+reallyPath+"/");
                //配置swagger资源路径
                registry.addResourceHandler("doc.html")
                        .addResourceLocations("classpath:/META-INF/resources/");
            }
        };
    }

    /**
     *  此方式可以灵活配置任意类型的序列化反序列化
     *
     * 使用雪花算法生成id，会导致id过大前端的js接收时，前端收到的id和数据库表的id
     * 不一致
     */
    @Bean
    public Jackson2ObjectMapperBuilderCustomizer builderCustomizer() {
        // 所有Long类型转换成String到前台
        return builder ->builder.serializerByType(Long.class, ToStringSerializer.instance);
    }
}
